package cn.znzz.cjm.service.impl;

import cn.znzz.cjm.constants.EmployeeConstants;
import cn.znzz.cjm.domain.Employee;
import cn.znzz.cjm.domain.LoginUser;
import cn.znzz.cjm.domain.Tenant;
import cn.znzz.cjm.dto.TenantEnteringDto;
import cn.znzz.cjm.feign.FeignProviderClient;
import cn.znzz.cjm.mapper.EmployeeMapper;
import cn.znzz.cjm.mapper.TenantMapper;
import cn.znzz.cjm.query.TenantQuery;
import cn.znzz.cjm.service.ITenantService;
import cn.znzz.cjm.util.AjaxResult;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chenjiangmin
 * @since 2021-12-15
 */
@Service
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements ITenantService {

    @Autowired
    private TenantMapper tenantMapper;

    @Autowired
    private FeignProviderClient feignProviderClient;

    @Autowired
    private EmployeeMapper employeeMapper;
    @Override
    public Page<Tenant> loadTenantType(TenantQuery query, Page<Tenant> page) {
        List<Tenant> list=tenantMapper.loadTenantType(query,page);
        page.setRecords(list);
        return page;
    }

    @Override
    public AjaxResult entering(TenantEnteringDto dto) {
        //先获取employee
        Employee employee = dto.getEmployee();
        //先保存auth服务中的t_login_user 然后将主键用来保存t_user_meal
        //再将t_login_user的主键用来保存t_employee 再将t_employee的主键用来保存t_tenant
        LoginUser loginUser = new LoginUser();
        loginUser.setUsername(employee.getUsername());
        loginUser.setPassword(employee.getPassword());
        loginUser.setMealid(dto.getMealId());
        //保存auth服务
        AjaxResult result = feignProviderClient.entering(loginUser);
        Date date = new Date();
        //成功先保存t_employee
        if(result.isSuccess()) {
            Integer id = (Integer) result.getResultObj();
            employee.setInputTime(date);
            employee.setLoginId(Long.valueOf(id));
            employee.setType(EmployeeConstants.ADMIN_EMPLOYEE);
            employeeMapper.insert(employee);
            //再保存t_tenant
            Tenant tenant = dto.getTenant();
            tenant.setRegisterTime(date);
            tenant.setAdminId(employee.getId());
            tenantMapper.insert(tenant);
        }
        return result;
    }
}
